//
//  QSTouchIDTool.m
//  myTest
//
//  Created by apple on 2017/9/14.
//  Copyright © 2017年 apple. All rights reserved.
//

#import "QSTouchIDTool.h"
#import "QSSV_HUDTool.h"

#import <LocalAuthentication/LocalAuthentication.h>
#import <UIKit/UIKit.h>

@implementation QSTouchIDTool
/**
 *  验证TouchID
 */
+ (void)verifyTouchIDWithFallbackTitle:(NSString *)fallBackTitle success:(void (^)())successBlock error:(void (^)(QSVerifyTouchIDState))errorBlock
{
    [self startVerifyTouchIDWithPolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics FallbackTitle:fallBackTitle success:successBlock error:errorBlock];
}

/**
 *  开始验证TouchID
 */
+ (void)startVerifyTouchIDWithPolicy:(LAPolicy )policy FallbackTitle:(NSString *)fallBackTitle success:(void (^)())successBlock error:(void (^)())errorBlock{
    // 创建上下文
    LAContext *context = [[LAContext alloc]init];
    context.localizedFallbackTitle = fallBackTitle;
    
    // 判断设备是否支持TouchID
    NSError* error = nil;
    if ([context canEvaluatePolicy:policy error:&error]) {
        [QSSV_HUDTool sv_showLoadingHUDWithoutMessage];
        
        [context evaluatePolicy:policy localizedReason:@"请验证已有指纹" reply:^(BOOL success, NSError * _Nullable error) {
            
            [QSSV_HUDTool sv_hideHUD];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                
                if (success)
                {
                    // 指纹识别成功，回主线程更新UI
                    dispatch_async(dispatch_get_main_queue(), ^{
                        if (policy == LAPolicyDeviceOwnerAuthentication)
                        {   // 密码验证成功
                            [self startVerifyTouchIDWithPolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics FallbackTitle:fallBackTitle success:successBlock error:errorBlock];
                        } else {
                            NSLog(@"指纹识别成功");
                            successBlock();
                        }
                    });
                }
                
                if (error) {
                    // 指纹识别失败，回主线程更新UI
                    dispatch_async(dispatch_get_main_queue(), ^{
                        LAError errorCode = error.code;
                        switch (errorCode) {
                                
                            case LAErrorAuthenticationFailed:
                            {
//                                NSLog(@"授权失败");
                                errorBlock(QSVerifyTouchIDState_VerifyFailed);
                            }
                                break;
                            case LAErrorUserCancel:
                            {
//                                NSLog(@"用户取消验证Touch ID");
                                errorBlock(QSVerifyTouchIDState_UserCancel);
                            }
                                break;
                            case LAErrorUserFallback:
                            {
//                                NSLog(@"用户选择输入密码，切换主线程处理");
                                errorBlock(QSVerifyTouchIDState_UserFallback);
                            }
                                break;
                            case LAErrorSystemCancel:
                            {
//                                NSLog(@"取消授权，如其他应用切入"); // -4 TouchID对话框被系统取消，例如按下Home或者电源键
                                [self startVerifyTouchIDWithPolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics FallbackTitle:fallBackTitle success:successBlock error:errorBlock];
                            }
                                break;
                            case LAErrorPasscodeNotSet:
                            {
//                                NSLog(@"设备系统未设置密码"); // -5
                                [self jumpToSetupTouchID];
                            }
                                break;
                            case LAErrorTouchIDNotAvailable:
                            {
//                                NSLog(@"设备未设置Touch ID"); // -6
                                [self jumpToSetupTouchID];
                            }
                                break;
                            case LAErrorTouchIDNotEnrolled:
                            {
//                                NSLog(@"用户未录入指纹"); // -7
                                [self jumpToSetupTouchID];
                            }
                                break;
                            case LAErrorTouchIDLockout:
                            {
//                                NSLog(@"Touch ID被锁，需要用户输入密码解锁");
                                [self startVerifyTouchIDWithPolicy:LAPolicyDeviceOwnerAuthentication FallbackTitle:fallBackTitle success:successBlock error:errorBlock];
                            }
                                break;
                            case LAErrorAppCancel:
                            {
//                                NSLog(@"用户不能控制情况下APP被挂起"); // -9
                            }
                                break;
                            case LAErrorInvalidContext:
                            {
//                                NSLog(@"LAContext传递给这个调用之前已经失效"); // -10
                                errorBlock(QSVerifyTouchIDState_InvalidContext);
                            }
                                break;
                        }
                        
                    });
                }
            });
        }];
    } else {
        NSLog(@"不支持TouchID");
        errorBlock(QSVerifyTouchIDState_WithoutTouchID);
    }
}

/**
 *  跳转到设置TouchID的界面
 */
+ (void)jumpToSetupTouchID
{
    NSURL *url = [NSURL URLWithString:@"App-Prefs:root=TOUCHID_PASSCODE"];
    if ([[UIApplication sharedApplication] canOpenURL:url])
    {
        [[UIApplication sharedApplication] openURL:url];
    }
}
@end
